package top.jle.spring.basic.util;

import jakarta.servlet.http.HttpServletRequest;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IPUtil {
    private static final List<String> IP_HEADERS = Arrays.asList("X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR");

    public static String getClientIp(HttpServletRequest request){
        Optional<String> ipOptional = IP_HEADERS.stream().map(request::getHeader).filter(ip->!isUnknown(ip)).findFirst();
        AtomicReference<String> clientIp = new AtomicReference<>(request.getRemoteAddr());
        ipOptional.ifPresent(clientIp::set);
        return clientIp.get().split(",")[0];
    }
    public static boolean isUnknown(String checkString) {
        return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
    }
}
